<template>
  <div class="c-bg-sgray theme-market">
    <div>
      <my-small-tabbar id="tab-bar" class="c-bg-white" v-if="!fId && !isFlashSales" :tabList="tabList" :tabIndex="promotionType" @changeTab="changeType"></my-small-tabbar>
      <div v-if="!fId && !isFlashSales" class="c-hh80 c-bg-white"></div>
      <div class="c-bg-white" v-for="(item, index) in flashSalesList" :key="index">
        <div v-if="item.otherStatus != 1 || fId" class=" c-pv24 c-mh24 c-flex-row c-bd-b1">
          <div class="c-ww210 c-hh140 c-br16 c-text-hidden c-flex-row c-flex-center c-flex-shrink0 c-p">
            <template v-if="promotionType == 1 || promotionType == 3 || promotionType == 4">
              <vip-custom-img :cover="item.cover" :coverUrl="item.cover || ''" :prodType="item.prodType" :imgClass="'c-w100 c-h imgCloseBig'" :fontClass="{
                boxStyle: 'c-pt30 c-pb48 c-pl12',
                name: 'c-fs32 c-text-ellipsis1 c-fw-b',
                duration: 'c-fs26'}" :content="item.vipInfo ? {name: item.vipInfo.name, duration: item.vipInfo.duration, durationType: item.vipInfo.durationType} : {}" />
            </template>
            <template v-else-if="promotionType == 2">
              <vip-custom-img :cover="item.cover" :imgClass="'imgCloseBig'" :fontClass="{
                boxStyle: 'c-pt30 c-pb48 c-pl12',
                name: 'c-fs32 c-text-ellipsis1 c-fw-b',
                duration: 'c-fs26'}" :content="{name: item.name, duration: item.duration, durationType: item.durationType}" v-if="item.cover && (item.cover.coverType==1 || item.cover.coverType==2)" />
              <CoverImg v-else coverSizeClass="c-w100 c-h c-text-hidden c-br16" imgClass="c-br16" :coverUrl="$addXossFilter(item.vipType==2||item.vipType==4?(item.vipType==2?require('@/assets/i/wap/course/vip.png'):require('@/assets/i/wap/course/svip.png')):item.avatar?item.avatar:require('@/assets/defult270.png'))" />
            </template>
            <template v-if="promotionType == 1 || promotionType == 2 || promotionType == 4">
              <div v-if="item.status==1 || item.status==2" :class="(themeName == 'mb3' || themeName == 'mb4') ? 'mb3-timeShow' : 'timeShow'">距{{item.status==1 ? '开始' : '结束'}}：
                <cj-clocker :time="timeFn(index)" format="%D 天 %H : %M : %S" @on-finish="finishFn(index)">
                </cj-clocker>
              </div>
              <div v-if="item.status==-1" :class="(themeName == 'mb3' || themeName == 'mb4') ? 'mb3-timeShow' : 'timeShow'">已结束</div>
            </template>
            <template v-if="promotionType == 3">
              <div v-if="item.sales.status==1 || item.sales.status==2" :class="(themeName == 'mb3' || themeName == 'mb4') ? 'mb3-timeShow' : 'timeShow'">距{{item.sales.status==1 ? '开始' : '结束'}}：
                <cj-clocker :time="timeFn(index)" format="%D 天 %H : %M : %S" @on-finish="finishFn(index)">
                </cj-clocker>
              </div>
              <div v-if="item.sales.status==-1" :class="(themeName == 'mb3' || themeName == 'mb4') ? 'mb3-timeShow' : 'timeShow'">已结束</div>
            </template>
          </div>
          <div class="c-flex-column c-ml20 c-w100 c-justify-sb">
            <div class="c-fs24 c-fc-xblack c-text-ellipsis2">{{promotionType == 1 ? item.title : promotionType == 4 ? (item.prodType == 7 ? (item.prodName + `(${item.ticketName})`) : item.prodName) : (promotionType == 2 ? item.name:(item.prodType == 7 ? (item.name + '(' + item.atName + ')') : item.name))}}</div>
            <div>
              <div class="c-fs18 c-fc-gray c-text-decoration-through c-pt16" v-if="!$isWxAppIos()">原价{{'￥' | iosPriceFilter}}{{promotionType == 2 ? item.price : item.prodPrice}}</div>
              <div class="c-flex-row c-aligni-center">
                <div class="c-fs24 c-fc-xmlred c-w0 c-flex-grow1" v-if="!$isWxAppIos()">
                  <span class="c-fs20 c-mr4">{{promotionType == 1 ? '拼团价' : promotionType == 4 ? '砍价享' : (promotionType == 2 ? '助力价' : (Number(item.price) == 0 ? '限时免费' :  item.sales.tags==''?'限时折扣':item.sales.tags))}}</span>
                  <span class="c-fs20 c-fw600">{{'￥' | iosPriceFilter}}</span>
                  <span class="c-fs26 c-fw600">{{promotionType == 2 ? '0.00' : promotionType == 4 ? item.reservePrice : (promotionType == 1 ? (item.captainPriceType == 2 ? `${item.captainPrice}起`:item.captainPrice) : item.price)}}</span>
                </div>
                <div v-if="item.isSaleOut == 0" @click="goToDetail(index)" class="c-fc-white c-fs22 c-flex-row c-flex-center c-ww116 c-hh48 c-br25 c-bg-dd">停止售卖</div>
                <template v-else>
                  <div v-if="promotionType == 1 || promotionType == 2" class="c-fc-white c-fs22 c-flex-row c-flex-center c-ww116 c-hh48 c-lh48 c-br25" :class="item.status == 1 ? 'theme-fc theme-bg-10' : (item.status == 2 ? 'theme-bg-gradient' : 'c-bg-dd')" @click="goToDetail(index)">{{item.status==1 ? '去看看' : (item.status==2 ? (promotionType == 1 ? '去拼团' : '助力领取') : '已结束')}}</div>
                  <div v-if="promotionType == 3 && (item.limit == 0 || (item.limit > item.sellCount))" class="c-fc-white c-fs22 c-flex-row c-flex-center c-ww116 c-hh48 c-lh48 c-br25" :class="item.sales.status == 1 ? 'theme-fc theme-bg-10' : (item.sales.status == 2 ? 'theme-bg-gradient' : 'c-bg-dd')" @click="goToDetail(index)">{{item.sales.status==1 ? '去看看' : (item.sales.status==2 ? '马上抢' : '已结束')}}</div>
                  <div v-if="promotionType == 3 && item.limit > 0 && (item.limit <= item.sellCount)" class="c-fc-white c-fs22 c-flex-row c-flex-center c-ww116 c-hh48 c-lh48 c-br25 c-bg-dd">已售罄</div>
                  <div v-if="promotionType == 4" class="c-fc-white c-fs22 c-flex-row c-flex-center c-ww116 c-hh48 c-lh48 c-br25" :class="item.status == 1 ? 'c-bg-dd' : (item.status == 2 && item.userType == -1) ? 'theme-bg-gradient' : (item.status == 2 && item.userType == 1) ? 'theme-fc theme-bg-10':''" @click="clickBargainDetail(index)">{{item.status == 1 ? '发起砍价' : (item.status == 2 && item.userType == 1) ? '正在砍价' : (item.status == 2 && item.userType == -1) ? '发起砍价' : ''}}</div>
                </template>
              </div>
            </div>
          </div>
        </div>
      </div>
      <loading-status-tem :dataStatus="dataStatus" noDataText="暂无商品"></loading-status-tem>
    </div>
    <nav-bottom-bar :itemIndex="6" v-if="showNavBottomBar"></nav-bottom-bar>
  </div>
</template>
<script>
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import NavBottomBar from "@/components/templates/common/navBottomBar.vue";
import MySmallTabbar from "@/components/templates/common/MySmallTabbar.vue";
import VipCustomImg from "@/components/templates/common/VipCustomImg.vue";
import CoverImg from '@/components/templates/common/coverImg.vue';
import { utilJs } from "@/utils/common.js";
import { goDetails } from "@/utils/goDetails.js";
var pageIndex = 1
let LIMIT = 10;
export default {
  name: 'FlashSalesList',
  components: {
    loadingStatusTem,
    NavBottomBar,
    MySmallTabbar,
    VipCustomImg,
    CoverImg
  },
  data() {
    return {
      theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : "mb5_default",
      themeName: localStorage.getItem('themeName') ? localStorage.getItem('themeName') : 'mb5',
      searchName: '',
      dataStatus: 'HAS_MORE_DATA',
      flashSalesList: [],
      flashSalesInfo: {},
      showNavBottomBar: false,
      promotionType: 1, // 营销类型
      fId: null,
      isFlashSales: false,
      cfrom: global.ckFrom,
      shartTitle: "",
      tabList: [],
      fromHome: false,
      prodType: '',
      collage: 0,
      task: 0,
      flash: 0,
      bargain: 0
    }
  },
  methods: {
    iosAppRouteChange(toPath) {
      if (utilJs.isIOSApp()) {
        window.webkit.messageHandlers.iosWechatRoute.postMessage(toPath);
      } else if (utilJs.isAndoridNewApp()) {
        let data = {
          path: toPath
        }
        window.androidWechatRoute.doAction(JSON.stringify(data))
      } else {
        this.$routerGo(this, "push", { path: toPath });
      }
    },
    // startSearch(e) {
    //   this.searchName = e.searchValue;
    //   pageIndex = 1;
    //   this.flashSalesList = [];
    //   utilJs.toPageScrollTop();
    //   this.initData();
    // },
    initData() {
      if (this.fId) {
        this.getListByFid()
      } else {
        this.getList()
      }
    },
    // 获取列表
    getList() {
      if (this.dataStatus == 'LOADING') {
        return;
      }
      this.dataStatus = 'LOADING';
      let productType = this.promotionType == 1 ? this.collage : this.promotionType == 2 ? this.task : this.promotionType == 3 ? this.flash : this.bargain
      utilJs.getMethod(
        `${global.apiurl}company/getMarketingLists?type=${this.promotionType}&page=${pageIndex}&limit=${LIMIT}&name=${this.searchName}&prodType=${this.prodType}${(this.collage == 0 && this.task == 0 && this.flash == 0 && this.bargain == 0) ? '' : '&productType=' + productType}`,
        res => {
          if (pageIndex == 1) {
            this.flashSalesList = res.data;
          } else {
            this.flashSalesList = [...this.flashSalesList, ...res.data];
          }
          if (res.data && (res.data.length < LIMIT)) {
            this.dataStatus = pageIndex == 1 && res.data.length == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
          } else {
            this.dataStatus = 'HAS_MORE_DATA';
            pageIndex++;
          }
          //友情灌溉后台传过来的是btnStatus
          if (this.promotionType == 2) {
            for (let i = 0; i < this.flashSalesList.length; i++) {
              this.flashSalesList[i].status = this.flashSalesList[i].btnStatus;
            }
          }
        },
        failRes => {
          this.dataStatus = 'DATA_ERROR';
        }
      );
    },
    // 某个活动下的限时购
    getListByFid() {
      if (this.dataStatus == 'LOADING') {
        return;
      }
      this.dataStatus = 'LOADING';
      utilJs.getMethod(
        global.apiurl + "sales/getSalesLists?fId=" + this.fId + '&page=' + pageIndex + '&limit=' + LIMIT + '&name=' + this.searchName,
        res => {
          if (pageIndex == 1) {
            this.flashSalesList = res.data;
          } else {
            this.flashSalesList = [...this.flashSalesList, ...res.data];
          }
          if (res.data && (res.data.length < LIMIT)) {
            this.dataStatus = pageIndex == 1 && res.data.length == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
          } else {
            this.dataStatus = 'HAS_MORE_DATA';
            pageIndex++;
          }
        },
        failRes => {
          this.dataStatus = 'DATA_ERROR';
        }
      );
    },
    clickBargainDetail(index) {
      let query = {}
      let prodId = this.flashSalesList[index].prodType == this.cfrom.activity ? this.flashSalesList[index].extraId : this.flashSalesList[index].prodId
      if ((this.flashSalesList[index].prodType == this.cfrom.vip || this.flashSalesList[index].prodType == this.cfrom.svip) && this.flashSalesList[index].status < 3) {
        query.isBargain = true;
      }
      goDetails(this, this.flashSalesList[index].prodType, prodId, query, (this.flashSalesList[index].courseType || 0), 1);
    },
    goToDetail(index) {
      let type = this.flashSalesList[index].prodType;
      if (this.promotionType == 2) {
        // 跳转到对应的详情页面 好友灌溉接口约定的prodType  0视频，1音频，2图文，3课程，4专栏，5vip升级页面，6测评，7交互测评，8语音测评，9知识套餐，10打卡，11训练营 ，12社群，13约课，14直播，15电子书，16资料库
        // 将好友灌溉接口约定的prodType 转为 goDetails.js中typeToUrl的key值
        let typeArr = [5, 5, 5, 5, 9, 1, 11, 75, 77, 61, 41, 78, 10, 53, 51, 142, 8];
        type = typeArr[Number(type)];
      }
      let query = {}
      let prodId = type == this.cfrom.activity ? this.flashSalesList[index].activityId
      : type == this.cfrom.edu ? this.flashSalesList[index].jwSalesId : this.flashSalesList[index].prodId
      if (this.promotionType == 1 || this.promotionType == 3) {
        if ((type == this.cfrom.collageVip || type == this.cfrom.flashSalesVip || type == this.cfrom.vip || type == this.cfrom.collageSvip || type == this.cfrom.flashSalesSvip || type == this.cfrom.svip) && (this.flashSalesList[index].status == 1 || this.flashSalesList[index].status == 2)) {
          if ((type == this.cfrom.flashSalesVip || type == this.cfrom.vip || type == this.cfrom.flashSalesSvip || type == this.cfrom.svip) && this.promotionType == 3) {
            query.isSales = true;
          } else {
            query.isCollage = true;
          }
        }
      } else if (this.promotionType == 2 && type == this.cfrom.vip && (this.flashSalesList[index].btnStatus == 1 || this.flashSalesList[index].btnStatus == 2)) {
        query.isFa = true;
        prodId = this.flashSalesList[index].faId
      }
      goDetails(this, type, prodId, query, (this.flashSalesList[index].courseType || 0), 1);
    },
    changeType(type) {
      if (this.dataStatus == 'LOADING') {
        return;
      }
      pageIndex = 1;
      this.flashSalesList = [];
      this.promotionType = type;
      this.getList();
    },
    timeFn: function (index) {
      let stime = '';
      let etime = '';
      let nowTime = (new Date()).getTime();
      if (this.promotionType == 2) {
        stime = this.flashSalesList ? utilJs.getTimeByDate(this.flashSalesList[index].startAt) : 0;
        etime = this.flashSalesList ? utilJs.getTimeByDate(this.flashSalesList[index].endAt) : 0;
      } else if (this.promotionType == 3) {
        stime = this.flashSalesList ? utilJs.getTimeByDate(this.flashSalesList[index].sales.startTime) : 0;
        etime = this.flashSalesList ? utilJs.getTimeByDate(this.flashSalesList[index].sales.endTime) : 0;
      } else {
        stime = this.flashSalesList ? utilJs.getTimeByDate(this.flashSalesList[index].startTime) : 0;
        etime = this.flashSalesList ? utilJs.getTimeByDate(this.flashSalesList[index].endTime) : 0;
      }
      //.status 1未开始,2进行中,-1已结束
      let time = '';
      if (stime > nowTime) {
        if (this.promotionType == 3) {
          this.flashSalesList[index].sales.status = 1;
        } else {
          this.flashSalesList[index].status = 1;
        }
        time = stime;
      } else if (etime > nowTime) {
        if (this.promotionType == 3) {
          this.flashSalesList[index].sales.status = 2;
        } else {
          this.flashSalesList[index].status = 2;
        }
        time = etime;
      } else {
        if (this.promotionType == 3) {
          this.flashSalesList[index].sales.status = -1;
        } else {
          this.flashSalesList[index].status = -1;
        }
      }
      return time;
    },
    finishFn: function (index) {
      if (this.promotionType == 3) {
        if (this.flashSalesList[index].sales.status == 1) {
          this.flashSalesList[index].sales.status = 2;
        } else {
          this.flashSalesList[index].sales.status = -1;
        }
      } else {
        if (this.flashSalesList[index].status == 1) {
          this.flashSalesList[index].status = 2;
        } else {
          this.flashSalesList[index].status = -1;
        }
      }
    },
    //分享
    wechatShare: function () {
      let title = this.fId ? this.shartTitle : '特惠活动列表';
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?refereeId=${localStorage.getItem("userId")}&prodType=${this.prodType}`;
      if (this.fId) {
        shareUrl = `${shareUrl}&fId=${this.fId}`;
      }
      let shareDesc = "点击查看详情";
      utilJs.wechatConfig(shareUrl, title, "", shareDesc);
    },
    //手机端分享
    appShare: function () {
      let title = this.fId ? this.shartTitle : '特惠活动列表';
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?refereeId=${localStorage.getItem("userId")}&prodType=${this.prodType}`;
      if (this.fId) {
        shareUrl = `${shareUrl}&fId=${this.fId}`;
      }
      let shareDesc = "点击查看详情";
      utilJs.appShareTrue(title, "", shareUrl, shareDesc);
    },
    windowScrollFunction() {
      utilJs.handleLoading(() => {
        if (this.dataStatus == 'HAS_MORE_DATA' && this.flashSalesList.length > 0) {
          this.initData();
        }
      });
    },
    FrsInitData() {
      pageIndex = 1;
      this.searchName = '';
      this.dataStatus = 'HAS_MORE_DATA';
      this.flashSalesList = [];
      this.initData();
    }
  },
  activated() {
    this.fId = this.$route.query.fId || null; // 是否是某个活动下的限时购
    this.isFlashSales = this.$route.query.isFlashSales || null; //  自定义模板限时购查看更多进入，只显示限时购列表
    this.prodType = this.$route.query.prodType || '';
    if (this.fId || this.isFlashSales) {
      this.promotionType = 3;
    }
    if (utilJs.checkNeedInitData(this.flashSalesList, pageIndex) || this.fromHome) {
      if (this.fId || this.isFlashSales) {
        this.FrsInitData();
      } else {
        let promotionTags = [{title: '限时购', index: 3}, {title: '拼团', index: 1}, {title: '友情灌溉', index: 2}, {title: '砍价购', index: 4}];
        this.tabList = [];
        if (this.$route.query.collage || this.$route.query.task || this.$route.query.flash || this.$route.query.bargain) {
          this.collage = this.$route.query.collage || 0;
          this.task = this.$route.query.task || 0;
          this.flash = this.$route.query.flash || 0;
          this.bargain = this.$route.query.bargain || 0;
          promotionTags.forEach(item => {
            if ((item.index == 3 && this.flash != 0) || (item.index == 1 && this.collage != 0) || (item.index == 2 && this.task != 0) || (item.index == 4 && this.bargain != 0)) {
              this.tabList.push(item)
            }
          })
          this.promotionType = this.tabList[0] ? this.tabList[0].index : 3;
          this.FrsInitData();
        } else {
          utilJs.getMethod(global.apiurl + "sales/getMarketingShowOrder", res => {
            if (this.tabList.length == 0 && res && res.length > 0) {
              for (let i = 0; i < res.length; i++) {
                this.tabList.push(promotionTags[res[i] - 1])
              }
              this.promotionType = this.tabList[0] ? this.tabList[0].index : 3;
            }
            this.FrsInitData();
          });
        }
      }
    }
    if (this.fId) {
      utilJs.getMethod(
        global.apiurl + "sales/getSalesInfo?fId=" + this.fId,
        res => {
          setDocumentTitle(res.name);// eslint-disable-line
          this.shartTitle = res.name;
        }
      );
    } else {
      setDocumentTitle("最新活动");// eslint-disable-line
    }

    // if (companyAuth.companyNav && companyAuth.companyNav.length > 0) {
    //   let arrClockFilter = companyAuth.companyNav.filter((item) => {
    //     return item.navType == 6;
    //   });
    //   this.showNavBottomBar = arrClockFilter.length > 0;
    // }
    this.wechatShare();
    window.addEventListener('scroll', this.windowScrollFunction);
  },
  deactivated() {
    // this.dataStatus = 'NO_MORE_DATA';
    window.removeEventListener('scroll', this.windowScrollFunction);
  },
  watch: {
    $route: function (to, from) {
      this.fId = this.$route.query.fId || null;
      if (from.path == '/' || from.path == '/homePage/microPage/microPage') {
        this.fromHome = true
        if (this.fId) {
          this.promotionType = 3;
        } else {
          // this.promotionType = 1;
        }
      } else {
        this.fromHome = false
      }
    }
  },
}
</script>
<style scoped>
#tab-bar {
  position: fixed;
  width: 100%;
  background-color: #fff;
  z-index: 10;
  padding-bottom: 10px;
}
.timeShow {
  font-size: 0.45rem;
  color: #fff;
  line-height: .7rem;
  width: 100%;
  text-align: center;
  background-color: rgba(0, 0, 0, 0.5);
  position: absolute;
  bottom: 0;
  left: 0;
  padding: .15rem 0;
}
.mb3-timeShow {
  font-size: 0.45rem;
  color: #fff;
  line-height: .75rem;
  width: 100%;
  text-align: center;
  background: linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.6));
  position: absolute;
  bottom: 0;
  left: 0;
  padding: .15rem 0;
}
</style>
